package io.renren.modules.vastFinance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.Result;
import com.tencent.common.pojo.StatusCode;
import io.renren.common.utils.BankCardTools;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.vastFinance.dao.BankcardDao;
import io.renren.modules.vastFinance.dao.UsersDao;
import io.renren.modules.vastFinance.entity.BankCard;
import io.renren.modules.vastFinance.entity.BankcardEntity;
import io.renren.modules.vastFinance.entity.UsersEntity;
import io.renren.modules.vastFinance.service.BankcardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("bankcardService")
public class BankcardServiceImpl extends ServiceImpl<BankcardDao, BankcardEntity> implements BankcardService {

    @Autowired
    UsersDao usersDao;
    @Autowired
    BankcardDao bankcardDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BankcardEntity> page = this.page(
                new Query<BankcardEntity>().getPage(params),
                new QueryWrapper<BankcardEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Result verifyBankCard(BankCard bankCard, Integer userId) {
        // 获取结构
        Result result = BankCardTools.verifyBankCard(bankCard);
        Map<String,Object> map = (Map<String, Object>) result.getData();
        // 认证成功 银行卡表新增数据，获取自增主键后赋值给user表字段card_id
        if (map.get("status").equals("01")) {

            BankcardEntity bankcardEntity = new BankcardEntity();
            bankcardEntity.setPhone(bankCard.getPhoneNumber());
            bankcardEntity.setCardNo(bankCard.getCardNumber());
            bankcardEntity.setCardholder(bankCard.getName());
            bankcardEntity.setIdentityId(bankCard.getIdNumber());
            bankcardDao.insert(bankcardEntity);

            QueryWrapper<UsersEntity> usersEntityQueryWrapper = new QueryWrapper<>();
            usersEntityQueryWrapper.eq("user_id",userId);
            UsersEntity usersEntity = usersDao.selectOne(usersEntityQueryWrapper);
            usersEntity.setCardId(bankcardEntity.getCardId());
            usersDao.update(usersEntity,usersEntityQueryWrapper);
        }
        return result;
    }

    @Override
    public Result<BankcardEntity> getBankCard(Integer cardId) {
        return new Result(StatusCode.OK,"查询成功",true,bankcardDao.selectById(cardId));
    }

}